package com.shjy.driver.util;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;


import com.shjy.driver.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.NOTIFICATION_SERVICE;

public class AntUtils {

    public static void  saveBoolAttr(Context context, String key, Boolean value){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key,value);
        editor.commit();
    }

    public static boolean getBoolAttr(Context context, String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(key,true);
    }

    public static void  saveStringAttr(Context context, String key, String value){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key,value);
        editor.commit();
    }

    public static String getStringAttr(Context context, String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        return sharedPreferences.getString(key,"");
    }

    public static void saveStringSetAttr(Context context, String key, String[] values){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Set<String> siteno = new HashSet<String>();
        if(values!=null && values.length>0){
            for(int i=0; i<values.length; i++){
                siteno.add(values[i]);
            }
        }
        editor.putStringSet(key,siteno);
        editor.commit();
    }

    public static Set<String> getStringSetAttr(Context context, String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        Set<String> siteno = new HashSet<String>();
        return sharedPreferences.getStringSet(key,siteno);
    }

    public static void  saveIntAttr(Context context, String key, int value){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key,value);
        editor.commit();
    }

    public static int getIntAttrWithDef(Context context, String key, int def){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        return sharedPreferences.getInt(key,def);
    }

    public static int getIntAttr(Context context, String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking", Context.MODE_PRIVATE);
        return sharedPreferences.getInt(key,-1);
    }

    public static String getDeviceUUID(Context context) {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        return uniqueId+ System.currentTimeMillis();
    }

    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Error";
    }

    public static int getVersionCode(Context context){
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String maskTelephone(String tel) {
        if (TextUtils.isEmpty(tel)) {
            throw new NullPointerException("telephone must be not null");
        }

        if (tel.length() != 11) {
            throw new NullPointerException("telephone number is not available");
        }

        return tel.substring(0, 3) + "****" + tel.substring(7, 11);
    }

    public static String getDistanceString(int distance) {
        if (distance < 1000) {
            return distance + "米";
        } else {
            float dd = distance / 1000.0f;
            return (float) (Math.round(dd * 100)) / 100 + "公里";
        }
    }

    static public boolean hasSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    public static String getAppMetaInfo(Context context, String key){
        String value = null;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            value = appInfo.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

    private static final String regex = "[\\u4e00-\\u9fa5]";
    private static final Pattern chinese_pattern = Pattern.compile(regex);
    public static boolean isChineseChar(char input){
        Matcher matcher = chinese_pattern.matcher(String.valueOf(input));
        return matcher.find();
    }

    public static boolean isDigitChar(char input){
        return String.valueOf(input).matches("^[a-zA-Z0-9]+$");
    }

    public static String getDeviceInfo(Context context) {
        try{
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if( TextUtils.isEmpty(device_id) ){
                device_id = mac;
            }

            if( TextUtils.isEmpty(device_id) ){
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static boolean checkAvailableNetWork(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if(connectivityManager == null){
            return false;
        }else{
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean checkNetWork(Context context, int netType){
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean hasNetWork = true;
        if(networkInfo == null || !networkInfo.isAvailable()){
            hasNetWork = false;
            return hasNetWork;
        }

        if(netType == networkInfo.getType()){
            return hasNetWork;
        }else{
            return false;
        }
    }


    public static String decimalToDMS(double coord) {
        String output, degrees, minutes, seconds;

        // gets the modulus the coordinate divided by one (MOD1).
        // in other words gets all the numbers after the decimal point.
        // e.g. mod := -79.982195 % 1 == 0.982195
        //
        // next get the integer part of the coord. On other words the whole number part.
        // e.g. intPart := -79

        double mod = coord % 1;
        int intPart = (int)coord;

        //set degrees to the value of intPart
        //e.g. degrees := "-79"

        degrees = String.valueOf(intPart);

        // next times the MOD1 of degrees by 60 so we can find the integer part for minutes.
        // get the MOD1 of the new coord to find the numbers after the decimal point.
        // e.g. coord :=  0.982195 * 60 == 58.9317
        //	mod   := 58.9317 % 1    == 0.9317
        //
        // next get the value of the integer part of the coord.
        // e.g. intPart := 58

        coord = mod * 60;
        mod = coord % 1;
        intPart = (int)coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }

        // set minutes to the value of intPart.
        // e.g. minutes = "58"
        minutes = String.valueOf(intPart);

        //do the same again for minutes
        //e.g. coord := 0.9317 * 60 == 55.902
        //e.g. intPart := 55
        coord = mod * 60;
        if (coord < 0) {
            // Convert number to positive if it's negative.
            coord *= -1;
        }
       /* intPart = (int)coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }*/

        // set seconds to the value of intPart.
        // e.g. seconds = "55"
//        seconds = String.valueOf(intPart);
        seconds = String.valueOf(coord);

        // I used this format for android but you can change it
        // to return in whatever format you like
        // e.g. output = "-79/1,58/1,56/1"
        output = degrees + "/1," + minutes + "/1," + seconds + "/1";

        //Standard output of D°M′S″
        //output = degrees + "°" + minutes + "'" + seconds + "\"";

        return output;
    }

    public static final String formatTitle(String title){
        int spanIndex = title.indexOf("<span>");
        if(spanIndex > 0){
            return title.substring(0,spanIndex);
        }
        return title;
    }

    public static final void repeatAlarmService(Context context, int minute, Class clazz){
        long intervalMillis = minute * 60*1000;
        Intent intent = new Intent(context,clazz);
        PendingIntent pendingIntent = PendingIntent.getService(context,1,intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),intervalMillis,pendingIntent);
    }

    public static final void cancelAlarmService(Context context, Class clazz){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        Intent intent = new Intent(context,clazz);
        PendingIntent pendingIntent = PendingIntent.getService(context,1,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(pendingIntent);
    }


    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static boolean isToday(String input)  {
        boolean isToday = false;
        if(TextUtils.isEmpty(input)){
            return isToday;
        }

        try {
            Date date = simpleDateFormat.parse(input);
            Calendar gregorianCalendar = GregorianCalendar.getInstance();
            gregorianCalendar.setTime(date);

            Calendar nowCalendar = GregorianCalendar.getInstance();
            nowCalendar.setTime(new Date());

            isToday = (gregorianCalendar.get(Calendar.DAY_OF_YEAR) - nowCalendar.get(Calendar.DAY_OF_YEAR) == 0);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isToday;
    }

    public static String formateDate(Date date){
        return simpleDateFormat.format(date);
    }

    public static String getIMSI(Context context){
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceID = telephonyManager.getDeviceId();
        try{
            if(deviceID==null || "".equals(deviceID) || " ".equals(deviceID)){
                deviceID = "357888888888888";
            }
            if(deviceID!=null && deviceID.length()>15){
                deviceID = deviceID.substring(0,15);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return deviceID;
    }

    public static String getUUID(Context context){
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String uuid = telephonyManager.getSimSerialNumber();
        try{
            if(uuid==null || "".equals(uuid) || " ".equals(uuid)){
                uuid = "89860118888888888";
            }
            if(uuid!=null && uuid.length()>20){
                uuid = uuid.substring(0,20);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return uuid;
    }

    public static String getTerminalSequenceNum(){
        return Build.SERIAL;
    }

    public static int getScreenWidth(Context context){
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getWidth();
    }

    public static void sendConnectIcon(Context context){
        AntUtils.sendNotification(context,R.drawable.i_transport_statusbar,"正在传数据");
    }

    public static void sendTranstionOk(Context context){
        AntUtils.cancelNotification(context,R.drawable.i_transport_statusbar);
        AntUtils.sendNotification(context, R.drawable.i_ok_statusbar,"数据传输成功");
    }

    public static void sendTranstionFail(Context context){
        AntUtils.cancelNotification(context,R.drawable.i_transport_statusbar);
        AntUtils.sendNotification(context,R.drawable.i_waring_statusbar,"数据传输失败");
    }

    public static void sendNotification(Context context, int resId, String notificationMessage){
        NotificationManager mNM = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(resId).setContentTitle(notificationMessage).setContentText(notificationMessage);
        mBuilder.setContentIntent(null);
        mBuilder.setOngoing(true);
        /*Notification notification = new Notification(resId,notificationMessage,System.currentTimeMillis());
        notification.flags = Notification.FLAG_NO_CLEAR;*/
        mNM.notify(resId, mBuilder.build());
    }

    public static void cancelNotification(Context context, int id){
        NotificationManager mNM = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        mNM.cancel(id);
    }

    public static void sleep(Context context, String tag){
        PowerManager pm =(PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,tag);
        wl.acquire();
        wl.release();
    }

    public static boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        return result;
    }

    public static void sendRepeat(Context context, long intervalTime, Class clazz){
        Intent serviceIntent = new Intent(context,clazz);
        AlarmManager alertManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getService(context,0,serviceIntent,0);
        alertManager.setRepeating(AlarmManager.RTC_WAKEUP,(new Date()).getTime(),intervalTime,pendingIntent);
    }


    public static String formateCarNumber(String carNumber){

        String formateCarNumber = "";
        if(!TextUtils.isEmpty(carNumber)){
            char[] charArray = carNumber.toCharArray();
            String[] subArray = new String[charArray.length];
            StringBuffer formateBuffer = new StringBuffer();
            for(int c=0;c<charArray.length;c++){
                subArray[c] = String.valueOf(charArray[c]);
                formateBuffer.append("%s");
                if(c == 0){
                    formateBuffer.append(" ");
                }
            }
            formateCarNumber = String.format(formateBuffer.toString(),subArray);
        }
        return formateCarNumber;
    }

    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

    public static void sendNotifyRingTone(Context context, String tip, int rawType){

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri ringUri = Uri.parse("android.resource://" + context.getPackageName() + "/"+rawType);//RingtoneManager.getDefaultUri(ringType);
        Notification notification = new NotificationCompat.Builder(context)
                .setTicker(tip).setSound(ringUri)
                .setContentTitle(tip).setContentText(tip).setSound(ringUri).build();
        nm.notify(R.string.app_name,notification);
    }

    public static String getLocalMacAddressFromWifiInfo(Context context){
        String mac = "";
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            mac = info.getMacAddress();

            if(TextUtils.isEmpty(mac)){
                NetworkInterface ne= NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
                byte[] byteMac = ne.getHardwareAddress();
                mac = byte2hex(byteMac);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return mac;
    }

    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer(b.length);
        String stmp = "";
        int len = b.length;
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
                hs = hs.append("0").append(stmp);
            else {
                hs = hs.append(stmp);
            }
        }
        return String.valueOf(hs);
    }

    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }

        return "";
    }

    public static String getMac(){
        String str="";
        String macSerial="";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }

    public static String getMacAddress(){
 /*获取mac地址有一点需要注意的就是android 6.0版本后，以下注释方法不再适用，不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址，这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
        //        String macAddress= "";
//        WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        macAddress = wifiInfo.getMacAddress();
//        return macAddress;

        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }
    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    public static int getScreenOffTime(Context context) {
        int screenOffTime = 0;
        try {
            screenOffTime = Settings.System.getInt(context.getContentResolver(),
                    Settings.System.SCREEN_OFF_TIMEOUT);
        } catch (Exception localException) {

        }
        return screenOffTime;
    }
}
